package cn.wolfcode.wolfcodemall.controller.fore;

import cn.wolfcode.wolfcodemall.domain.*;
import cn.wolfcode.wolfcodemall.qo.PageQo;
import cn.wolfcode.wolfcodemall.service.AddressService;
import cn.wolfcode.wolfcodemall.service.OrderService;
import cn.wolfcode.wolfcodemall.service.ProductService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 订单相关请求
 */
@Controller
public class OrderController {
    @Autowired
    private AddressService addressService;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderService orderService;
    //订单确认页面
    @RequestMapping("/order/create/{productId}")
    public String orderConfirmPage(Model model,@PathVariable Integer productId,Short product_number){
        //查询所有的省份信息
        List<Address> addressList = addressService.findRoot();
        //根据省份id查询市级信息
        List<Address> cityList = addressService.findList(addressList.get(0).getAddressAreaid());
        //根据市的id查询县区信息
        List<Address> districtList = addressService.findList(cityList.get(0).getAddressAreaid());

        model.addAttribute("addressList",addressList);
        model.addAttribute("cityList",cityList);
        model.addAttribute("districtList",districtList);

        //==================================================
        //根据商品id查询到商品信息
        Product product = productService.selectById(productId);
        //将商品信息存储到订单项对象中
        ProductOrderItem productOrderItem = new ProductOrderItem();
        productOrderItem.setProductOrderItemProduct(product);
        productOrderItem.setProductorderitemNumber(product_number);
        productOrderItem.setProductorderitemPrice(product.getProductSalePrice().multiply(new BigDecimal(product_number+"")));

        //将订单项对存储到集合中
        List<ProductOrderItem> productOrderItemList = new ArrayList<ProductOrderItem>();
        productOrderItemList.add(productOrderItem);

        //将订单项集合带到页面中显示
        model.addAttribute("orderItemList",productOrderItemList);
        model.addAttribute("orderTotalPrice",productOrderItem.getProductorderitemPrice());

        return "/fore/productBuyPage";
    }

    //订单的确认(创建)  单订单项
    @RequestMapping("/order")
    @ResponseBody
    public String createOrderByOne(ProductOrder productOrder, ProductOrderItem productOrderItem, HttpSession session){
        //保存订单信息以及订单项信息
        User user = (User) session.getAttribute("user");

        //保存订单和订单项信息
        JSONObject jsonObject = new JSONObject();
        try{
            orderService.createOrderByOne(productOrder,productOrderItem,user.getUserId());
            //订单创建成功
            jsonObject.put("success",true);
            //跳转路径   付款页面
            jsonObject.put("url","/order/pay/" + productOrder.getProductorderId());

        }catch(Exception e){
            //创建失败
            jsonObject.put("success",false);
        }

        return jsonObject.toJSONString();
    }

    //支付页面
    @RequestMapping("/order/pay/{orderId}")
    public String orderPayPage(@PathVariable Integer orderId,Model model){
        //根据订单id查询订单信息
        ProductOrder productOrder = orderService.findProductOrderByOrderId(orderId);
        model.addAttribute("productOrder",productOrder);

        //订单总价格
        List<ProductOrderItem> productOrderItemList = productOrder.getProductOrderItemList();
        BigDecimal orderTotalPrice = new BigDecimal("0");
        for (ProductOrderItem productOrderItem : productOrderItemList) {
            //将每一个订单项价格向加
            orderTotalPrice = orderTotalPrice.add(productOrderItem.getProductorderitemPrice());
        }
        model.addAttribute("orderTotalPrice",orderTotalPrice);

        return "/fore/productPayPage";
    }

    //订单支付
    @RequestMapping(value = "/order/pay/{orderId}",method = RequestMethod.PUT)
    @ResponseBody
    public String orderPay(@PathVariable Integer orderId){
        //对订单支付
        JSONObject jsonObject = new JSONObject();
        try{
            orderService.orderPay(orderId);
            jsonObject.put("success",true);
            //支付成功页面
            jsonObject.put("url","/order/pay/success/" + orderId);
        }catch(Exception e){
            jsonObject.put("success",false);
        }
        return jsonObject.toJSONString();

    }

    //支付成功页面
    @RequestMapping("/order/pay/success/{orderId}")
    public String paySuccessPage(@PathVariable Integer orderId,Model model){
        //根据id查询订单信息
        ProductOrder productOrder = orderService.findProductOrderByOrderId(orderId);
        //获取订单中区的地址id，根据id查询区地址对象
        String addressId = productOrder.getProductorderAddress();
        //县区地址对象
        Address address = addressService.findById(addressId);
        //市对象
        Address address1 = addressService.findById(address.getAddressRegionid());
        //省对象
        Address address2 = addressService.findById(address1.getAddressRegionid());

        //为订单设置详细地址
        productOrder.setProductorderDetailAddress(address2.getAddressName() + " " + address1.getAddressName() + " " + address.getAddressName() + " " + productOrder.getProductorderDetailAddress());

        model.addAttribute("productOrder",productOrder);

        List<ProductOrderItem> productOrderItemList = productOrder.getProductOrderItemList();
        BigDecimal orderTotalPrice = new BigDecimal("0");
        for (ProductOrderItem productOrderItem : productOrderItemList) {
            orderTotalPrice = orderTotalPrice.add(productOrderItem.getProductorderitemPrice());
        }
        model.addAttribute("orderTotalPrice",orderTotalPrice);

        return "/fore/productPaySuccessPage";
    }

    //订单列表请求
    @RequestMapping(value = "/order/list",method = RequestMethod.GET)
    public String orderListPage(HttpSession session, PageQo qo,Model model,
                                @RequestParam(value = "status", required = false) Integer status){
        //查询当前登录用户订单信息
        Object user = session.getAttribute("user");
        if(user == null){
            //未登录
            return "redirect:/login";
        }
        User usr = (User) user;

        //已登录
        //根据用户id查询订单信息
        PageInfo<ProductOrder> pageResult = orderService.selectOrderByUserId(qo, usr.getUserId(),status);

        model.addAttribute("pageResult",pageResult);
        model.addAttribute("status",status);

        return "/fore/orderListPage";
    }

    //加入购物车
    @RequestMapping("/orderItem/create/{productId}")
    @ResponseBody
    public String addCart(@PathVariable Integer productId,Short product_number,HttpSession session){
        User user = (User) session.getAttribute("user");
        JSONObject jsonObject = new JSONObject();
        try{
            orderService.addCart(productId,product_number,user.getUserId());
            jsonObject.put("success",true);
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("success",false);
        }
        return jsonObject.toJSONString();
    }

    //购物车页面
    @RequestMapping("/cart")
    public String cartPage(HttpSession session,Model model){
        //查询当前登录用户的购物车信息
        Object user = session.getAttribute("user");
        if(user == null){
            return "redirect:/login";
        }
        User usr = (User) user;
        //查购物车信息
        List<ProductOrderItem> orderItemList = orderService.findCart(usr.getUserId());

        model.addAttribute("orderItemList",orderItemList);

        return "/fore/productBuyCarPage";
    }
    //改变购物车商品数量
    @ResponseBody
    @RequestMapping(value = "/orderItemNumberChange/{orderItemId}",produces = "application/json;charset=utf-8")
    public String orderItemNumberChange(@PathVariable Integer orderItemId,Short productNumber){
        JSONObject jsonObject = new JSONObject();
        try {
            orderService.changeOrderItemNumber(orderItemId,productNumber);
            jsonObject.put("success",true);
        }catch (Exception e){
            jsonObject.put("success",false);
        }
       return jsonObject.toJSONString();

    }
    //购物车结算
    @RequestMapping("/order/create/byCart")
    public String orderConfirmPageBuCart(Integer[] order_item_list,Model model){
        //查询所有的省份信息
        List<Address> addressList = addressService.findRoot();
        //根据省份id查询市级信息
        List<Address> cityList = addressService.findList(addressList.get(0).getAddressAreaid());
        //根据市的id查询县区信息
        List<Address> districtList = addressService.findList(cityList.get(0).getAddressAreaid());

        model.addAttribute("addressList",addressList);
        model.addAttribute("cityList",cityList);
        model.addAttribute("districtList",districtList);

        List<ProductOrderItem> orderItemList = new ArrayList<ProductOrderItem>();
        //查询每一个购物车信息
        BigDecimal orderTotalPrice = new BigDecimal("0");

        for (Integer orderItemId : order_item_list) {
            ProductOrderItem productOrderItem = orderService.findCartById(orderItemId);
            orderItemList.add(productOrderItem);

            orderTotalPrice = orderTotalPrice.add(productOrderItem.getProductorderitemPrice());

        }

        model.addAttribute("orderItemList",orderItemList);
        model.addAttribute("orderTotalPrice",orderTotalPrice);
        return "/fore/productBuyPage";

    }
    //删除购物车商品
    @RequestMapping("/orderItem/{id}")
    @ResponseBody
    public String upload(@PathVariable("id") Integer id){
        // 删除功能
       orderService.deleteById(id);


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", true);
        return jsonObject.toJSONString();
    }

   // 订单创建，多订单项

    @RequestMapping(value = "/order/list",method = RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String createOrderByList(ProductOrder productOrder,String orderItemJSON,HttpSession session){
        User user = (User) session.getAttribute("user");
        JSONObject jsonObject = new JSONObject();
        try {
            orderService.createOrderByList(productOrder,orderItemJSON,user.getUserId());
            jsonObject.put("success",true);
            jsonObject.put("url","/order/pay/"+ productOrder.getProductorderId());
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("success",false);
        }
       return jsonObject.toJSONString();
    }

    @RequestMapping("/order/close/{orderIdHidden}")
    @ResponseBody
    public String orderDelete(@PathVariable("orderIdHidden") Integer orderIdHidden,Integer orderStatus){

        JSONObject jsonObject = new JSONObject();

        int i = orderService.logicDeleteByOrderId(orderIdHidden,orderStatus);
        if (i == 1){
            jsonObject.put("success",true);
        }
        return jsonObject.toJSONString();
    }

    @RequestMapping("/orderList")
    public String  orderList(){
        return "/fore/orderListPage";
    }

    @RequestMapping("/order/delivery/{productorderId}")
    public String orderDelivery(@PathVariable("productorderId") Integer productorderId ){

        return "/fore/orderListPage";
    }
    @RequestMapping("/order/confirm/{orderId}")
    public String confirmOrder(@PathVariable("orderId") Integer orderId) {
        orderService.logicDeleteByOrderId(orderId, 3);

        return "/fore/orderListPage";
    }

}


